package com.ht.modules.system.online.cgform.util;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.ht.api.ISysBaseAPI;
import com.ht.entity.DictModel;
import com.ht.entity.SysPermissionDataRule;
import com.ht.exception.JeecgBootException;
import com.ht.query.QueryRuleEnum;
import com.ht.utils.SpringContextUtils;
import com.ht.utils.UUIDGenerator;
import com.ht.utils.jsonschema.CommonProperty;
import com.ht.utils.jsonschema.JsonSchemaDescrip;
import com.ht.utils.jsonschema.JsonschemaUtil;
import com.ht.utils.jsonschema.validate.DictProperty;
import com.ht.utils.jsonschema.validate.NumberProperty;
import com.ht.utils.jsonschema.validate.PopupProperty;
import com.ht.utils.jsonschema.validate.StringProperty;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.shiro.SecurityUtils;
import com.ht.query.QueryGenerator;

import com.ht.entity.LoginUser;
import com.ht.utils.DateUtils;
import com.ht.utils.oConvertUtils;

import com.ht.modules.system.online.cgform.entity.OnlCgformButton;
import com.ht.modules.system.online.cgform.entity.OnlCgformEnhanceJava;
import com.ht.modules.system.online.cgform.entity.OnlCgformEnhanceJs;
import com.ht.modules.system.online.cgform.entity.OnlCgformField;
import com.ht.modules.system.online.cgform.entity.OnlCgformHead;
import com.ht.modules.system.online.cgform.entity.OnlCgformIndex;
import com.ht.modules.system.online.config.exception.DBException;
import com.ht.modules.system.online.config.util.DbTableUtil;
import org.jeecgframework.poi.excel.entity.params.ExcelExportEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class CgformUtil {
    private static final Logger log = LoggerFactory.getLogger(CgformUtil.class);
    public static final String SQL_SELECT = "SELECT ";
    public static final String SQL_FROM = " FROM ";
    public static final String SQL_AND = " AND ";
    public static final String SQL_COUNT = " COUNT(*) ";
    public static final String SQL_WHERE_TRUE = " where 1=1  ";
    public static final String SQL_ORDER = " ORDER BY ";
    public static final String SQL_ASC = "asc";
    public static final String SQL_DESC = "desc";
    public static final String SQL_EQ = "=";
    public static final String SQL_GE = ">=";
    public static final String SQL_LE = "<=";
    public static final String CREATE_TIME = "CREATE_TIME";
    public static final String CREATE_BY = "CREATE_BY";
    public static final String UPDATE_TIME = "UPDATE_TIME";
    public static final String UPDATE_BY = "UPDATE_BY";
    public static final String SYS_ORG_CODE = "SYS_ORG_CODE";
    public static final int QUERY_FIELD_SHOW_NUM = 2;
    public static final String SQL_SQ = "'";
    public static final String SQL_COMMA = ",";
    public static final String QUERY_MODE_SINGLE = "single";
    public static final String P_KEY = "id";
    public static final String YES = "1";
    public static final String SYNC_FORCE = "force";
    public static final String SYNC_NORMAL = "normal";
    private static final String enhanceJsButtonCode = "beforeAdd,beforeEdit,afterAdd,afterEdit,beforeDelete,afterDelete,mounted,created";

    public CgformUtil() {
    }

    public static void getAutoListBaseSql(String tbname, List<OnlCgformField> fieldList, StringBuffer sb) {
        sb.append("SELECT ");
        int size = fieldList.size();
        boolean has = false;
        for (int i = 0; i < size; ++i) {
            OnlCgformField item = fieldList.get(i);
            if ("id".equals(item.getDbFieldName())) {
                has = true;
            }
            if (i == size - 1) {
                sb.append(item.getDbFieldName()).append(" ");
            } else {
                sb.append(item.getDbFieldName()).append(",");
            }
        }
        if (!has) {
            sb.append(",id");
        }
        sb.append(" FROM ").append(tbname);
    }

    public static String getAutoListConditionSql(List<OnlCgformField> fieldList, Map<String, Object> params) {
        StringBuffer sb = new StringBuffer();
        String dataBase = "";

        try {
            dataBase = DbTableUtil.getDatabaseType();
        } catch (Exception  e) {
            e.printStackTrace();
        }
        Map<String, SysPermissionDataRule> ruleMap = QueryGenerator.getRuleMap();
        Iterator<?> var5 = ruleMap.keySet().iterator();
        while (var5.hasNext()) {
            String c = (String) var5.next();
            if (oConvertUtils.isNotEmpty(c) && c.startsWith("SQL_RULES_COLUMN")) {
                sb.append(" AND (").append(QueryGenerator.getSqlRuleValue(ruleMap.get(c).getRuleValue())).append(")");
            }
        }

        var5 = fieldList.iterator();

        while (var5.hasNext()) {
            OnlCgformField item = (OnlCgformField) var5.next();
            String field = item.getDbFieldName();
            String dbtype = item.getDbType();
            if (ruleMap.containsKey(field)) {
                addRuleToStringBuffer(ruleMap.get(field), field, dbtype, sb);
            }
            if (ruleMap.containsKey(oConvertUtils.camelNames(field))) {
                addRuleToStringBuffer(ruleMap.get(field), field, dbtype, sb);
            }
            if (1 == item.getIsQuery()) {
                Object value_begin;
                if ("single".equals(item.getQueryMode())) {
                    value_begin = params.get(field);
                    if (value_begin != null) {
                        if ("ORACLE".equals(dataBase)) {
                            sb.append(" AND ").append(field).append("=").append(" to_date('").append(value_begin).append("','yyyy-MM-dd HH24:mi:ss')");
                        } else {
                            boolean isString = !OnlineDbHandler.isNumField(dbtype);
                            String fieldCondition = QueryGenerator.getSingleQueryConditionSql(field, "", value_begin, isString);
                            sb.append(" AND ").append(fieldCondition);
                        }
                    }
                } else {
                    value_begin = params.get(field + "_begin");
                    if (value_begin != null) {
                        sb.append(" AND ").append(field).append(">=");
                        if (OnlineDbHandler.isNumField(dbtype)) {
                            sb.append(value_begin);
                        } else if ("ORACLE".equals(dataBase)) {
                            sb.append(" to_date('").append(value_begin).append("','yyyy-MM-dd HH24:mi:ss')");
                        } else {
                            sb.append("'").append(value_begin).append("'");
                        }
                    }

                    Object value_end = params.get(field + "_end");
                    if (value_end != null) {
                        sb.append(" AND ").append(field).append("<=");
                        if (OnlineDbHandler.isNumField(dbtype)) {
                            sb.append(value_end);
                        } else if ("ORACLE".equals(dataBase)) {
                            sb.append(" to_date('").append(value_end).append("','yyyy-MM-dd HH24:mi:ss')");
                        } else {
                            sb.append("'").append(value_end).append("'");
                        }
                    }
                }
            }
        }

        return sb.toString();
    }

    public static Map<String, Object> getParameterMap(HttpServletRequest request) {
        Map<?, ?> properties = request.getParameterMap();
        Map<String, Object> returnMap = new HashMap();
        Iterator<?> entries = properties.entrySet().iterator();
        String name = "";
        String value = "";

        for (Object valueObj; entries.hasNext(); returnMap.put(name, value)) {
            Entry<String, Object> entry = (Entry) entries.next();
            name = entry.getKey();
            valueObj = entry.getValue();
            if (!"_t".equals(name) && null != valueObj) {
                if (!(valueObj instanceof String[] values)) {
                    value = valueObj.toString();
                } else {
                    for (String s : values) {
                        value = s + ",";
                    }
                    value = value.substring(0, value.length() - 1);
                }
            } else {
                value = "";
            }
        }

        return returnMap;
    }

    public static JSONObject getJsonSchemaByCgformFieldList(List<OnlCgformField> fieldList, List<String> disabledFieldNameList) {
        new JSONObject();
        List<String> required = new ArrayList<>();
        List<CommonProperty> props = new ArrayList<>();
        ISysBaseAPI sysBaseAPI = SpringContextUtils.getBean(ISysBaseAPI.class);
        for (OnlCgformField item : fieldList) {
            String field = item.getDbFieldName();
            if (!"id".equals(field)) {
                String title = item.getDbFieldTxt();
                if ("1".equals(item.getFieldMustInput())) {
                    required.add(field);
                }
                String filedShowType = item.getFieldShowType();
                CommonProperty prop;
                if (OnlineDbHandler.isNumField(item.getDbType())) {
                    prop = new NumberProperty(field, title, "number");
                } else if ("list,radio,checkbox,list_multi".contains(filedShowType)) {
                    List<DictModel> include = new ArrayList<>();
                    if (oConvertUtils.isNotEmpty(item.getDictTable())) {
                        include = sysBaseAPI.queryTableDictItemsByCode(item.getDictTable(), item.getDictText(), item.getDictField());
                    } else if ("sel_search".equals(filedShowType)) {
                        new DictProperty(field, title, item.getDictTable(), item.getDictField(), item.getDictText());
                    } else if (oConvertUtils.isNotEmpty(item.getDictField())) {
                        include = sysBaseAPI.queryDictItemsByCode(item.getDictField());
                    }
                    prop = new StringProperty(field, title, filedShowType, item.getDbLength(), include);
                } else if ("popup".equals(filedShowType)) {
                    prop = new PopupProperty(field, title, item.getDictTable(), item.getDictText(), item.getDictField());
                } else {
                    prop = new StringProperty(field, title, filedShowType, item.getDbLength());
                }
                if (disabledFieldNameList.contains(field)) {
                    prop.setDisabled(true);
                }
                prop.setOrder(item.getOrderNum());
                props.add(prop);
            }
        }
        JSONObject json;
        JsonSchemaDescrip descrip;
        if (!required.isEmpty()) {
            descrip = new JsonSchemaDescrip(required);
        } else {
            descrip = new JsonSchemaDescrip();
        }
        json = JsonschemaUtil.getJsonSchema(descrip, props);
        return json;
    }

    public static JSONObject getSubJsonSchemaByCgformFieldList(String entityDescrib, List<OnlCgformField> fieldList) {
        new JSONObject();
        List<String> required = new ArrayList<>();
        List<CommonProperty> props = new ArrayList<>();
        ISysBaseAPI sysBaseAPI = SpringContextUtils.getBean(ISysBaseAPI.class);
        for (OnlCgformField item : fieldList) {
            String field = item.getDbFieldName();
            if (!"id".equals(field)) {
                String title = item.getDbFieldTxt();
                if ("1".equals(item.getFieldMustInput())) {
                    required.add(field);
                }

                String filedShowType = item.getFieldShowType();
                String dictCode = item.getDictField();
                CommonProperty prop;
                if (OnlineDbHandler.isNumField(item.getDbType())) {
                    prop = new NumberProperty(field, title, "number");
                } else if ("list,radio,checkbox,list_multi".contains(filedShowType)) {
                    List<DictModel> include = sysBaseAPI.queryDictItemsByCode(dictCode);
                    prop = new StringProperty(field, title, filedShowType, item.getDbLength(), include);
                } else {
                    prop = new StringProperty(field, title, filedShowType, item.getDbLength());
                }
                prop.setOrder(item.getOrderNum());
                props.add(prop);
            }
        }

        JSONObject json = JsonschemaUtil.getSubJsonSchema(entityDescrib, required, props);
        return json;
    }

    public static Map<String, Object> getFormDataSaveSql(String tbname, List<OnlCgformField> fieldList, JSONObject json) {
        StringBuilder sb1 = new StringBuilder();
        StringBuilder sb2 = new StringBuilder();
        String dataBase = "";
        try {
            dataBase = DbTableUtil.getDatabaseType();
        } catch (Exception e) {
            e.printStackTrace();
        }
        Map<String, Object> params = new HashMap<>();
        boolean hasKey = false;
        String keyFieldValue = null;
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if (sysUser == null) {
            throw new JeecgBootException("");
        }
        Iterator<?> var10 = fieldList.iterator();
        while (true) {
            while (var10.hasNext()) {
                OnlCgformField item = (OnlCgformField) var10.next();
                String key = item.getDbFieldName();
                if (null == key) {
                    log.info("--------online������������������Ƶ��ֶ�------->>{}", item.getId());
                } else {
                    initSystemFileds(item, sysUser, json, "CREATE_BY", "CREATE_TIME", "SYS_ORG_CODE");
                    if ((item.getIsShowForm() == 1 || !oConvertUtils.isEmpty(item.getMainField())) && json.get(key) != null) {
                        String sqlValue;
                        if ("".equals(json.get(key))) {
                            sqlValue = item.getDbType();
                            if (OnlineDbHandler.isNumField(sqlValue) || sqlValue.toLowerCase().contains("date")) {
                                continue;
                            }
                        }

                        if ("id".equalsIgnoreCase(key)) {
                            hasKey = true;
                            keyFieldValue = json.getString(key);
                        } else {
                            sb1.append(",").append(key);
                            sqlValue = OnlineDbHandler.initMybatisValueWithJdbcType(dataBase, item, json, params);
                            sb2.append(",").append(sqlValue);
                        }
                    }
                }
            }

            if (hasKey) {
                if (oConvertUtils.isEmpty(keyFieldValue)) {
                    keyFieldValue = UUIDGenerator.generate();
                }
            } else {
                keyFieldValue = UUIDGenerator.generate();
            }

            String sql = "insert into " + tbname + "(" + "id" + sb1 + ") values(" + "'" + keyFieldValue + "'" + sb2 + ")";
            params.put("execute_sql_string", sql);
            log.info("--��̬������sql-->{}", sql);
            return params;
        }
    }

    public static Map<String, Object> getFormDataEditSql(String tbname, List<OnlCgformField> fieldList, JSONObject json) {
        StringBuilder sb = new StringBuilder();
        Map<String, Object> params = new HashMap<>();
        String dataBase = "";

        try {
            dataBase = DbTableUtil.getDatabaseType();
        } catch (Exception e) {
            e.printStackTrace();
        }
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if (sysUser == null) {
            throw new JeecgBootException("online�޸ı������쳣:ϵͳδ�ҵ���ǰ��½�û���Ϣ");
        } else {
            Iterator<?> var7 = fieldList.iterator();
            while (true) {
                while (var7.hasNext()) {
                    OnlCgformField item = (OnlCgformField) var7.next();
                    String key = item.getDbFieldName();
                    if (null == key) {
                        log.info("--------online�޸ı��������������Ƶ��ֶ�------->>" + item.getId());
                    } else {
                        initSystemFileds(item, sysUser, json, "UPDATE_BY", "UPDATE_TIME", "SYS_ORG_CODE");
                        if (item.getIsShowForm() == 1 && !"id".equals(key)) {
                            String dbType;
                            if ("".equals(json.get(key))) {
                                dbType = item.getDbType();
                                if (OnlineDbHandler.isNumField(dbType) || dbType.toLowerCase().contains("date")) {
                                    continue;
                                }
                            }
                            dbType = OnlineDbHandler.initMybatisValueWithJdbcType(dataBase, item, json, params);
                            sb.append(key).append("=").append(dbType).append(",");
                        }
                    }
                }

                String condition = sb.toString();
                if (condition.endsWith(",")) {
                    condition = condition.substring(0, condition.length() - 1);
                }

                String sql = "update " + tbname + " set " + condition + " where 1=1  " + " AND " + "id" + "=" + "'" + json.getString("id") + "'";
                log.info("--��̬���༭sql-->" + sql);
                params.put("execute_sql_string", sql);
                return params;
            }
        }
    }

    public static String getSelectFormSql(String tbname, List<OnlCgformField> fieldList, String id) {
        return getSelectSubFormSql(tbname, fieldList, "id", id);
    }

    public static String getSelectSubFormSql(String tbname, List<OnlCgformField> fieldList, String linkField, String value) {
        StringBuffer sb = new StringBuffer();
        sb.append("SELECT ");
        int size = fieldList.size();
        boolean has = false;

        for (int i = 0; i < size; ++i) {
            String key = fieldList.get(i).getDbFieldName();
            if ("id".equals(key)) {
                has = true;
            }

            sb.append(key);
            if (size > i + 1) {
                sb.append(",");
            }
        }

        if (!has) {
            sb.append(",id");
        }

        sb.append(" FROM ").append(tbname).append(" where 1=1  ").append(" AND ").append(linkField).append("=").append("'").append(value).append("'");
        return sb.toString();
    }

    public static void initSystemFileds(OnlCgformField item, LoginUser sysUser, JSONObject json, String... systemFields) {
        String key = item.getDbFieldName();
        boolean need = false;
        String[] var6 = systemFields;
        int var7 = systemFields.length;

        for (int var8 = 0; var8 < var7; ++var8) {
            String field = var6[var8];
            if (key.toUpperCase().equals(field)) {
                if (item.getIsShowForm() == 1) {
                    if (json.get(key) == null) {
                        need = true;
                    }
                } else {
                    item.setIsShowForm(1);
                    need = true;
                }

                if (need) {
                    byte var11 = -1;
                    switch (field.hashCode()) {
                        case -909973894:
                            if (field.equals("CREATE_BY")) {
                                var11 = 0;
                            }
                            break;
                        case -99751974:
                            if (field.equals("SYS_ORG_CODE")) {
                                var11 = 4;
                            }
                            break;
                        case 837427085:
                            if (field.equals("UPDATE_BY")) {
                                var11 = 2;
                            }
                            break;
                        case 1609067651:
                            if (field.equals("UPDATE_TIME")) {
                                var11 = 3;
                            }
                            break;
                        case 1688939568:
                            if (field.equals("CREATE_TIME")) {
                                var11 = 1;
                            }
                    }

                    switch (var11) {
                        case 0:
                            json.put(key, sysUser.getUsername());
                            return;
                        case 1:
                            item.setFieldShowType("datetime");
                            json.put(key, DateUtils.formatDateTime());
                            return;
                        case 2:
                            json.put(key, sysUser.getUsername());
                            return;
                        case 3:
                            item.setFieldShowType("datetime");
                            json.put(key, DateUtils.formatDateTime());
                            return;
                        case 4:
                            json.put(key, sysUser.getOrgCode());
                    }
                }
                break;
            }
        }

    }

    public static boolean compareValue(Object oldvalue, Object newvalue) {
        if (oConvertUtils.isEmpty(oldvalue) && oConvertUtils.isEmpty(newvalue)) {
            return true;
        } else {
            return oldvalue.equals(newvalue);
        }
    }

    public static boolean databaseFieldIsChange(OnlCgformField oldColumn, OnlCgformField newColumn) {
        return !compareValue(oldColumn.getDbFieldName(), newColumn.getDbFieldName()) || !compareValue(oldColumn.getDbFieldTxt(), newColumn.getDbFieldTxt()) || !compareValue(oldColumn.getDbLength(), newColumn.getDbLength()) || !compareValue(oldColumn.getDbPointLength(), newColumn.getDbPointLength()) || !compareValue(oldColumn.getDbType(), newColumn.getDbType()) || !compareValue(oldColumn.getDbIsNull(), newColumn.getDbIsNull()) || !compareValue(oldColumn.getDbIsKey(), newColumn.getDbIsKey()) || !compareValue(oldColumn.getMainTable(), newColumn.getMainTable()) || !compareValue(oldColumn.getMainField(), newColumn.getMainField()) || !compareValue(oldColumn.getDbDefaultVal(), newColumn.getDbDefaultVal());
    }

    public static boolean databaseIndexIsChange(OnlCgformIndex oldIndex, OnlCgformIndex newIndex) {
        return !compareValue(oldIndex.getIndexName(), newIndex.getIndexName()) || !compareValue(oldIndex.getIndexField(), newIndex.getIndexField()) || !compareValue(oldIndex.getIndexType(), newIndex.getIndexType());
    }

    public static boolean databaseTableIsChange(OnlCgformHead oldTable, OnlCgformHead newTable) {
        return !compareValue(oldTable.getTableName(), newTable.getTableName()) || !compareValue(oldTable.getTableTxt(), newTable.getTableTxt());
    }

    public static String getQueryListDataCondition(String tbname, List<OnlCgformField> fieldList, Map<String, Object> params) {
        StringBuffer sb = new StringBuffer();
        StringBuffer selectField = new StringBuffer();
        Iterator var5 = fieldList.iterator();

        while (var5.hasNext()) {
            OnlCgformField item = (OnlCgformField) var5.next();
            String field = item.getDbFieldName();
            String dbtype = item.getDbType();
            if (item.getIsShowList() == 1) {
                selectField.append("," + field);
            }

            boolean isString;
            String fieldCondition;
            if (oConvertUtils.isNotEmpty(item.getMainField())) {
                isString = !OnlineDbHandler.isNumField(dbtype);
                fieldCondition = QueryGenerator.getSingleQueryConditionSql(field, "", params.get(field), isString);
                if (!"".equals(fieldCondition)) {
                    sb.append(" AND " + fieldCondition);
                }
            }

            if (item.getIsQuery() == 1) {
                if ("single".equals(item.getQueryMode())) {
                    if (params.get(field) != null) {
                        isString = !OnlineDbHandler.isNumField(dbtype);
                        fieldCondition = QueryGenerator.getSingleQueryConditionSql(field, "", params.get(field), isString);
                        if (!"".equals(fieldCondition)) {
                            sb.append(" AND " + fieldCondition);
                        }
                    }
                } else {
                    Object beginVal = params.get(field + "_begin");
                    if (beginVal != null) {
                        sb.append(" AND " + field + ">=");
                        if (OnlineDbHandler.isNumField(dbtype)) {
                            sb.append(beginVal.toString());
                        } else {
                            sb.append("'" + beginVal.toString() + "'");
                        }
                    }

                    Object endVal = params.get(field + "_end");
                    if (endVal != null) {
                        sb.append(" AND " + field + ">=");
                        if (OnlineDbHandler.isNumField(dbtype)) {
                            sb.append(endVal.toString());
                        } else {
                            sb.append("'" + endVal.toString() + "'");
                        }
                    }
                }
            }
        }

        return "SELECT id" + selectField.toString() + " FROM " + tbname + " where 1=1  " + sb.toString();
    }

    public static List<ExcelExportEntity> convertToExportEntity(List<OnlCgformField> lists, String pkField) {
        List<ExcelExportEntity> entityList = new ArrayList<>();

        for (int i = 0; i < lists.size(); ++i) {
            if ((null == pkField || !pkField.equals(((OnlCgformField) lists.get(i)).getDbFieldName())) && ((OnlCgformField) lists.get(i)).getIsShowList() == 1) {
                ExcelExportEntity entity = new ExcelExportEntity(((OnlCgformField) lists.get(i)).getDbFieldTxt(), ((OnlCgformField) lists.get(i)).getDbFieldName());
                int columnWidth = ((OnlCgformField) lists.get(i)).getDbLength() == 0 ? 12 : (((OnlCgformField) lists.get(i)).getDbLength() > 30 ? 30 : ((OnlCgformField) lists.get(i)).getDbLength());
                if (((OnlCgformField) lists.get(i)).getFieldShowType().equals("date")) {
                    entity.setFormat("yyyy-MM-dd");
                } else if (((OnlCgformField) lists.get(i)).getFieldShowType().equals("datetime")) {
                    entity.setFormat("yyyy-MM-dd HH:mm:ss");
                }

                entity.setWidth((double) columnWidth);
                entityList.add(entity);
            }
        }

        return entityList;
    }

    public static boolean checkClassOrSpringBeanIsExist(OnlCgformEnhanceJava onlCgformEnhanceJava) {
        String cgJavaType = onlCgformEnhanceJava.getCgJavaType();
        String cgJavaValue = onlCgformEnhanceJava.getCgJavaValue();
        if (oConvertUtils.isNotEmpty(cgJavaValue)) {
            try {
                if ("class".equals(cgJavaType)) {
                    Class clazz = Class.forName(cgJavaValue);
                    if (clazz == null || clazz.newInstance() == null) {
                        return false;
                    }
                }

                if ("spring".equals(cgJavaType)) {
                    Object obj = SpringContextUtils.getBean(cgJavaValue);
                    if (obj == null) {
                        return false;
                    }
                }
            } catch (Exception var4) {
                log.error(var4.getMessage(), var4);
                return false;
            }
        }

        return true;
    }

    public static void sortStringList(List<String> list) {
        list.sort((o1, o2) -> {
            if (o1 != null && o2 != null) {
                return Integer.compare(o1.compareTo(o2), 0);
            } else {
                return -1;
            }
        });
    }

    public static void sortStringList2(List<String> list) {
        list.sort((o1, o2) -> {
            if (o1 != null && o2 != null) {
                if (o1.length() > o2.length()) {
                    return 1;
                } else if (o1.length() < o2.length()) {
                    return -1;
                } else return Integer.compare(o1.compareTo(o2), 0);
            } else {
                return -1;
            }
        });
    }

    private static String converRuleValue(String value, boolean flag) {
        return flag ? "'" + QueryGenerator.converRuleValue(value) + "'" : QueryGenerator.converRuleValue(value);
    }

    private static void addRuleToStringBuffer(SysPermissionDataRule dataRule, String field, String dbtype, StringBuffer sb) {
        QueryRuleEnum rule = QueryRuleEnum.getByValue(dataRule.getRuleConditions());
        boolean isSq = !OnlineDbHandler.isNumField(dbtype);
        String value = converRuleValue(dataRule.getRuleValue(), isSq);
        if (value != null && rule != null) {
            switch (rule) {
                case GT:
                    sb.append(" AND " + field + " > " + value);
                    break;
                case GE:
                    sb.append(" AND " + field + ">=" + value);
                    break;
                case LT:
                    sb.append(" AND " + field + " > " + value);
                    break;
                case LE:
                    sb.append(" AND " + field + "<=" + value);
                    break;
                case EQ:
                    sb.append(" AND " + field + "=" + value);
                    break;
                case NE:
                    sb.append(" AND " + field + " <> " + value);
                    break;
                case IN:
                    sb.append(" AND " + field + " IN " + QueryGenerator.converRuleValue(value));
                    break;
                case LIKE:
                    sb.append(" AND " + field + " LIKE '%" + QueryGenerator.converRuleValue(value) + "%'");
                    break;
                case LEFT_LIKE:
                    sb.append(" AND " + field + " LIKE '%" + QueryGenerator.converRuleValue(value) + "'");
                    break;
                case RIGHT_LIKE:
                    sb.append(" AND " + field + " LIKE '" + QueryGenerator.converRuleValue(value) + "%'");
                    break;
                default:
                    log.info("--��ѯ����δƥ�䵽---");
            }

        }
    }

    public static String formateSQl(String sql, JSONObject json) {
        if (json == null) {
            return sql;
        } else {
            sql = sql.replace("#{UUID}", UUIDGenerator.generate());
            Set<String> varParams = QueryGenerator.getSqlRuleParams(sql);

            String key;
            for (Iterator var3 = varParams.iterator(); var3.hasNext(); sql = sql.replace("#{" + key + "}", json.getString(key))) {
                key = (String) var3.next();
            }

            return sql;
        }
    }

    public static String overwriteJs(String enhanceJs, List<OnlCgformButton> cgButtonList) {
        enhanceJs = overwriteJsByButtonStyle(enhanceJs, cgButtonList);
        String[] var2 = "beforeAdd,beforeEdit,afterAdd,afterEdit,beforeDelete,afterDelete,mounted,created".split(",");
        int var3 = var2.length;

        for (int var4 = 0; var4 < var3; ++var4) {
            String temp = var2[var4];
            Pattern p;
            Matcher m;
            if ("beforeAdd,afterAdd,mounted,created".indexOf(temp) >= 0) {
                p = Pattern.compile("(" + temp + "\\s*\\(\\)\\s*\\{)");
                m = p.matcher(enhanceJs);
                if (m.find()) {
                    enhanceJs = enhanceJs.replace(m.group(0), temp + "(that){const getAction=this._getAction,postAction=this._postAction,deleteAction=this._deleteAction;");
                }
            } else {
                p = Pattern.compile("(" + temp + "\\s*\\(row\\)\\s*\\{)");
                m = p.matcher(enhanceJs);
                if (m.find()) {
                    enhanceJs = enhanceJs.replace(m.group(0), temp + "(that,row){const getAction=this._getAction,postAction=this._postAction,deleteAction=this._deleteAction;");
                } else {
                    Pattern p2 = Pattern.compile("(" + temp + "\\s*\\(\\)\\s*\\{)");
                    Matcher m2 = p2.matcher(enhanceJs);
                    if (m2.find()) {
                        enhanceJs = enhanceJs.replace(m2.group(0), temp + "(that){const getAction=this._getAction,postAction=this._postAction,deleteAction=this._deleteAction;");
                    }
                }
            }
        }

        return returnEnhanceJsClass(enhanceJs);
    }

    public static void overwriteJs(OnlCgformEnhanceJs onlCgformEnhanceJs, String tbname, List<OnlCgformField> fieldList) {
        if (onlCgformEnhanceJs != null && !oConvertUtils.isEmpty(onlCgformEnhanceJs.getCgJs())) {
            String enhanceJs = onlCgformEnhanceJs.getCgJs();
            String onlChange = "onlChange";
            Pattern p = Pattern.compile("(" + tbname + "_" + onlChange + "\\s*\\(\\)\\s*\\{)");
            Matcher m = p.matcher(enhanceJs);
            if (m.find()) {
                enhanceJs = enhanceJs.replace(m.group(0), tbname + "_" + onlChange + "(){const getAction=this._getAction,postAction=this._postAction,deleteAction=this._deleteAction;");
                Iterator var7 = fieldList.iterator();

                while (var7.hasNext()) {
                    OnlCgformField field = (OnlCgformField) var7.next();
                    Pattern p1 = Pattern.compile("(" + field.getDbFieldName() + "\\s*\\(\\))");
                    Matcher m1 = p1.matcher(enhanceJs);
                    if (m1.find()) {
                        enhanceJs = enhanceJs.replace(m1.group(0), field.getDbFieldName() + "(that,event)");
                    }
                }
            }

            onlCgformEnhanceJs.setCgJs(enhanceJs);
        }
    }

    public static void overwriteJs(OnlCgformEnhanceJs onlCgformEnhanceJs, String tbname, List<OnlCgformField> fieldList, boolean isMain) {
        if (onlCgformEnhanceJs != null && !oConvertUtils.isEmpty(onlCgformEnhanceJs.getCgJs())) {
            String enhanceJs = onlCgformEnhanceJs.getCgJs();
            String onlChange = "onlChange";
            Pattern p = Pattern.compile("([^_]" + onlChange + "\\s*\\(\\)\\s*\\{)");
            Matcher m = p.matcher(enhanceJs);
            if (m.find()) {
                enhanceJs = enhanceJs.replace(m.group(0), onlChange + "(){const getAction=this._getAction,postAction=this._postAction,deleteAction=this._deleteAction;");
                Iterator var8 = fieldList.iterator();

                while (var8.hasNext()) {
                    OnlCgformField field = (OnlCgformField) var8.next();
                    Pattern p1 = Pattern.compile("(" + field.getDbFieldName() + "\\s*\\(\\))");
                    Matcher m1 = p1.matcher(enhanceJs);
                    if (m1.find()) {
                        enhanceJs = enhanceJs.replace(m1.group(0), field.getDbFieldName() + "(that,event)");
                    }
                }
            }

            onlCgformEnhanceJs.setCgJs(enhanceJs);
            overwriteJs(onlCgformEnhanceJs, tbname, fieldList);
        }
    }

    public static String returnEnhanceJsClass(String enhanceJs) {
        log.info("���յ���ǿJS", enhanceJs);
        return "class OnlineEnhanceJs{constructor(getAction,postAction,deleteAction){this._getAction=getAction;this._postAction=postAction;this._deleteAction=deleteAction;}" + enhanceJs + "}";
    }

    public static String overwriteJsByButtonStyle(String enhanceJs, List<OnlCgformButton> cgButtonList) {
        if (cgButtonList != null) {
            Iterator var2 = cgButtonList.iterator();

            while (true) {
                while (var2.hasNext()) {
                    OnlCgformButton button = (OnlCgformButton) var2.next();
                    String temp = button.getButtonCode();
                    Pattern p;
                    Matcher m;
                    if ("link".equals(button.getButtonStyle())) {
                        p = Pattern.compile("(" + temp + "\\s*\\(row\\)\\s*\\{)");
                        m = p.matcher(enhanceJs);
                        if (m.find()) {
                            enhanceJs = enhanceJs.replace(m.group(0), temp + "(that,row){const getAction=this._getAction,postAction=this._postAction,deleteAction=this._deleteAction;");
                        } else {
                            Pattern p2 = Pattern.compile("(" + temp + "\\s*\\(\\)\\s*\\{)");
                            Matcher m2 = p2.matcher(enhanceJs);
                            if (m2.find()) {
                                enhanceJs = enhanceJs.replace(m2.group(0), temp + "(that){const getAction=this._getAction,postAction=this._postAction,deleteAction=this._deleteAction;");
                            }
                        }
                    } else if ("button".equals(button.getButtonStyle()) || "form".equals(button.getButtonStyle())) {
                        p = Pattern.compile("(" + temp + "\\s*\\(\\)\\s*\\{)");
                        m = p.matcher(enhanceJs);
                        if (m.find()) {
                            enhanceJs = enhanceJs.replace(m.group(0), temp + "(that){const getAction=this._getAction,postAction=this._postAction,deleteAction=this._deleteAction;");
                        }
                    }
                }

                return enhanceJs;
            }
        } else {
            return enhanceJs;
        }
    }

    public static JSONArray getJEditableTableColumnsJson(List<OnlCgformField> fieldList) {
        JSONArray array = new JSONArray();
        ISysBaseAPI sysBaseAPI = (ISysBaseAPI) SpringContextUtils.getBean(ISysBaseAPI.class);
        Iterator var3 = fieldList.iterator();

        while (var3.hasNext()) {
            OnlCgformField item = (OnlCgformField) var3.next();
            String field = item.getDbFieldName();
            if (!"id".equals(field)) {
                JSONObject obj = new JSONObject();
                obj.put("title", item.getDbFieldTxt());
                obj.put("key", field);
                obj.put("width", "186px");
                obj.put("type", getJEditableTableColumnsType(item));
                obj.put("defaultValue", item.getDbDefaultVal());
                obj.put("placeholder", "������" + item.getDbFieldTxt());
                obj.put("validateRules", getValidateRules(item));
                if ("list".equals(item.getFieldShowType())) {
                    List<DictModel> include = new ArrayList<>();
                    if (oConvertUtils.isNotEmpty(item.getDictTable())) {
                        include = sysBaseAPI.queryTableDictItemsByCode(item.getDictTable(), item.getDictText(), item.getDictField());
                    } else if (oConvertUtils.isNotEmpty(item.getDictField())) {
                        include = sysBaseAPI.queryDictItemsByCode(item.getDictField());
                    }

                    obj.put("options", include);
                }

                array.add(obj);
            }
        }

        return array;
    }

    private static JSONArray getValidateRules(OnlCgformField item) {
        JSONArray array = new JSONArray();
        JSONObject json2;
        if (item.getDbIsNull() == 0 || "1".equals(item.getFieldMustInput())) {
            json2 = new JSONObject();
            json2.put("required", true);
            json2.put("message", item.getDbFieldTxt() + "����Ϊ��!");
            array.add(json2);
        }

        if (oConvertUtils.isNotEmpty(item.getFieldValidType())) {
            json2 = new JSONObject();
            json2.put("pattern", item.getFieldValidType());
            json2.put("message", item.getDbFieldTxt() + "��ʽ����ȷ");
            array.add(json2);
        }

        return array;
    }

    public static Map<String, Object> transLowerCaseMapKey(Map<String, Object> orgMap) {
        Map<String, Object> resultMap = new HashMap();
        if (orgMap != null && !orgMap.isEmpty()) {
            Set<String> keySet = orgMap.keySet();
            Iterator var3 = keySet.iterator();

            while (var3.hasNext()) {
                String key = (String) var3.next();
                String newKey = key.toLowerCase();
                resultMap.put(newKey, orgMap.get(key));
            }

            return resultMap;
        } else {
            return resultMap;
        }
    }

    public static List<Map<String, Object>> toLowerCasePageList(List<Map<String, Object>> list) {
        List<Map<String, Object>> select = new ArrayList<>();
        Iterator var2 = list.iterator();

        while (var2.hasNext()) {
            Map<String, Object> row = (Map) var2.next();
            Map<String, Object> resultMap = new HashMap();
            Set<String> keySet = row.keySet();
            Iterator var6 = keySet.iterator();

            while (var6.hasNext()) {
                String key = (String) var6.next();
                String newKey = key.toLowerCase();
                resultMap.put(newKey, row.get(key));
            }

            select.add(resultMap);
        }

        return select;
    }

    private static String getJEditableTableColumnsType(OnlCgformField item) {
        if ("checkbox".equals(item.getFieldShowType())) {
            return "checkbox";
        } else if ("list".equals(item.getFieldShowType())) {
            return "select";
        } else if ("datetime".equals(item.getFieldShowType())) {
            return "datetime";
        } else if ("date".equals(item.getFieldShowType())) {
            return "date";
        } else {
            return !"int".equals(item.getDbType()) && !"double".equals(item.getDbType()) && !"BigDecimal".equals(item.getDbType()) ? "input" : "inputNumber";
        }
    }
}
